import React, { useState, useEffect } from 'react';
import {
  ProFormText,
  ProFormTextArea,
  ProFormSelect
} from '@ant-design/pro-form';
import { Form, Modal, Row, Col, Card, TreeSelect, message, Table, Checkbox, Select, Input, Button, Space, Switch } from 'antd';
import { useIntl, FormattedMessage } from 'umi';
import type { TableListItem } from '../data.d';
import { getTreeList } from '../../../system/menu/service';

export type FormValueType = {} & Partial<TableListItem>;
const { Option } = Select;

export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  updateModalVisible: boolean;
  values: Partial<TableListItem>;
};


const columns = [
  {
    title: '字段名称',
    dataIndex: 'field_name',
    key: 'field_name',
  },
  {
    title: '字段描述',
    dataIndex: 'field_comment',
    key: 'field_comment',
  },
  {
    title: '添加编辑',
    dataIndex: 'field_operat',
    key: 'field_operat',
    render: (text, record) => (
      <Form.Item
        label="Sight"
        name={['field_operat']}
        fieldKey={[record.field_operat, 'sight']}
        rules={[{ required: true, message: 'Missing sight' }]}
      >
        <Checkbox></Checkbox>
      </Form.Item>

    ),
  },
  {
    title: '列表展示',
    dataIndex: 'field_list',
    key: 'field_list',
    render: (text, record) => (
      <Checkbox></Checkbox>
    ),
  },
  {
    title: '查询展示',
    dataIndex: 'field_query',
    key: 'field_query',
    render: (text, record) => (
      <Checkbox></Checkbox>
    ),
  },
  {
    title: '查询方式',
    dataIndex: 'query_type',
    key: 'query_type',
    render: (text, record) => (
      <Form.Item
        label="Sight"
        name={['field_operat']}
        fieldKey={[record.field_operat, 'sight']}
        rules={[{ required: true, message: 'Missing sight' }]}
      >
        <Select
          style={{ width: 120 }}
          placeholder="查询方式"
          optionFilterProp="children"
        >
          <Option value="="> 等于 </Option>
          <Option value="!="> 不等于 </Option>
          <Option value=">"> 大于 </Option>
          <Option value=">="> 大于等于 </Option>
          <Option value="<"> 小于 </Option>
          <Option value="<="> 小于等于 </Option>
          <Option value="like"> like </Option>
          <Option value="is null"> is null </Option>
          <Option value="is not null">
            is not null
          </Option>
        </Select>
      </Form.Item>

    ),
  },
  {
    title: '校验规则',
    dataIndex: 'verify_rule',
    key: 'verify_rule',
    render: (text, record) => (
      <Select
        style={{ width: 120 }}
        placeholder="校验规则"
        optionFilterProp="children"
      >
        <Option value="1"> 文本框 </Option>
        <Option value="2"> 文本域 </Option>
        <Option value="3"> 下拉框 </Option>
        <Option value="4"> 单选框 </Option>
        <Option value="5"> 复选框 </Option>
        <Option value="6"> 富文本 </Option>
        <Option value="7"> 日期控件 </Option>
        <Option value="8"> 上传控件 </Option>
      </Select>
    ),
  },
  {
    title: '选项内容',
    dataIndex: 'option_content',
    key: 'option_content',
    render: (text, record) => (
      <Input hidden={record.show_type == '3' || record.show_type == '4' || record.show_type == '5' ? true : false} placeholder="选项内容" />
    ),
  },
  {
    title: '默认值',
    dataIndex: 'default_value',
    key: 'default_value',
    render: (text, record) => (
      <Input placeholder="默认值" />
    ),
  },
  {
    title: '排序',
    dataIndex: 'order_by',
    key: 'order_by',
    render: (text, record) => (
      <Input placeholder="排序" />
    ),
  },
];


const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  const [form] = Form.useForm();
  const [showGenPath, setShowGenPath] = useState<boolean>(false);
  const [treeData, setTreeData] = useState<any>([]);
  const [menuId, setMenuId] = useState<any>('');
  const [data, setData] = useState<any>([]);
  const [fieldData, setFieldData] = useState<any>([]);
  const [tempType, setTempType] = useState<any>('0');
  

  useEffect(() => {
    if (form && !props.updateModalVisible) {
      form.resetFields();
    }
    if (props.values.gen_type == '1') {
      setShowGenPath(true);
    } else {
      setShowGenPath(false);
    }

    let myFieldData = [];
    // console.log(props.values.fieldList)
    for (var i = 0; i < props.values?.fieldList?.length || 0; i++) {
      if (props.values?.fieldList[i].field_operat == 'Y') {
        props.values.fieldList[i].f_operat = true;
      } else {
        props.values.fieldList[i].f_operat = false;
      }
      if (props.values?.fieldList[i].field_list == 'Y') {
        props.values.fieldList[i].f_list = true;
      } else {
        props.values.fieldList[i].f_list = false;
      }
      if (props.values?.fieldList[i].field_query == 'Y') {
        props.values.fieldList[i].f_query = true;
      } else {
        props.values.fieldList[i].f_query = false;
      }
      myFieldData.push({
          value: props.values.fieldList[i].field_name,
          label: props.values.fieldList[i].field_comment,
      })
    }
    setFieldData(myFieldData);
    setData(props.values?.fieldList || {})
    console.log(props.values.fieldList)
    findMenuList();
  }, [props.updateModalVisible]);

  const fommat = (arrayList: any, pidStr = "parent_id", idStr = "id", childrenStr = "children") => {
    arrayList.push({ 'name': '菜单信息', 'id': '1', 'parent_id': '0', 'dic_cascade': 'dic_1_', 'level_num': '0' })
    let listOjb = {}; // 用来储存{key: obj}格式的对象
    let treeList = []; // 用来储存最终树形结构数据的数组
    // 将数据变换成{key: obj}格式，方便下面处理数据
    for (let i = 0; i < arrayList.length; i++) {
      var data = arrayList[i];
      data.title = data.name;
      data.key = data.id;
      data.value = data.id;
      if (data.child_num == 0) {
        data.isLeaf = true;
      }
      listOjb[arrayList[i][idStr]] = data;
    }
    // 根据pid来将数据进行格式化
    for (let j = 0; j < arrayList.length; j++) {
      // 判断父级是否存在
      let haveParent = listOjb[arrayList[j][pidStr]];
      if (haveParent) {
        // 如果有没有父级children字段，就创建一个children字段
        !haveParent[childrenStr] && (haveParent[childrenStr] = []);
        // 在父级里插入子项
        haveParent[childrenStr].push(arrayList[j]);
      } else {
        // 如果没有父级直接插入到最外层
        treeList.push(arrayList[j]);
      }
    }
    return treeList;
  };

  const findMenuList = async () => {
    const hide = message.loading('正在查询');
    try {
      await getTreeList({}).then((res: any) => {
        const treeData = fommat(
          res.data,
          "parent_id"
        );
        let expandedKeys = [];
        expandedKeys.push('1');
        setTreeData(treeData);
      })
      hide();
      // message.success('数据查询成功');
      return true;
    } catch (error) {
      hide();
      // message.error('数据查询失败');
      return false;
    }
  };

  useEffect(() => {
    console.log(showGenPath)
  }, [showGenPath]);


  const intl = useIntl();
  let index = 0;
  const handleOk = () => {
    form.submit();
    if (index > 0) {
      props.onCancel()
    }
    index++;
  };
  const handleCancel = () => {
    props.onCancel()
  }
  const handleFinish = (values: any) => {
    for (var i = 0; i < values.fieldList?.length || 0; i++) {
      values.fieldList[i].field_operat = values?.fieldList[i].f_operat
      values.fieldList[i].field_list = values?.fieldList[i].f_list
      values.fieldList[i].field_query = values?.fieldList[i].f_query
    }
    props.onSubmit(values as any);
  };


  const selectMenuChange = (value: any) => {
    setMenuId(value);
  }

  // setInitValues(props.values);
  return (
    <Modal
      width={1000}
      title={intl.formatMessage({
        id: '操作',
        defaultMessage: '操作',
      })}
      visible={props.updateModalVisible}
      destroyOnClose
      onOk={handleOk} onCancel={handleCancel}
    // onFinish={props.onSubmit}
    // onVisibleChange={handleOk}
    // initialValues={props.values}
    >
      <Form
        form={form}
        onFinish={handleFinish}
        initialValues={props.values}
        layout="vertical"
      >
        <Card title="基础信息设置" style={{ width: '100%' }}>
          <Row gutter={[16, 16]}>
            <Col span={12} order={1}>
              <ProFormText
                label='表名称'
                rules={[
                  {
                    required: true,
                    message: "表名称不可为空。",
                  },
                ]}
                width="xl"
                name="table_name"
                placeholder="请输入表名称"
              />
            </Col>
            <Col span={12} order={2}>
              <ProFormText
                label='表描述'
                rules={[
                  {
                    required: true,
                    message: "表描述不可为空。",
                  },
                ]}
                width="xl"
                name="table_comment"
                placeholder="请输入表描述"
              />
            </Col>
          </Row>
          <Row gutter={[16, 16]}>
            <Col span={12} order={1}>
              <ProFormSelect
                width="xl"
                options={[
                  {
                    value: "0",
                    label: "单表",
                  },
                  {
                    value: "1",
                    label: "树表",
                  }
                ]}
                placeholder="请选择模板类型"
                name="temp_type"
                label="模板类型"
                fieldProps={{onChange:(val) => {
                  setTempType(val);
                }}}
              />
            </Col>
            <Col span={12} order={2}>
              <ProFormText
                label='生成包路径'
                rules={[
                  {
                    required: true,
                    message: "生成包路径不可为空。",
                  },
                ]}
                width="xl"
                name="pack_path"
                placeholder="请输入生成包路径"
              />
            </Col>
          </Row>
          <Row gutter={[16, 16]}>
            <Col span={12} order={1}>
              <ProFormText
                label='生成模块名'
                rules={[
                  {
                    required: true,
                    message: "生成模块名不可为空。",
                  },
                ]}
                width="xl"
                name="mod_name"
                placeholder="请输入生成模块名"
              />
            </Col>
            <Col span={12} order={2}>
              <ProFormText
                label='生成业务名'
                rules={[
                  {
                    required: true,
                    message: "生成业务名不可为空。",
                  },
                ]}
                width="xl"
                name="bus_name"
                placeholder="请输入生成业务名"
              />
            </Col>
          </Row>
          <Row gutter={[16, 16]}>
            <Col span={12} order={1}>
              <ProFormText
                label='功能名称'
                rules={[
                  {
                    required: true,
                    message: "功能名称不可为空。",
                  },
                ]}
                width="xl"
                name="menu_name"
                placeholder="请输入功能名称"
              />
            </Col>
            <Col span={12} order={2}>
              <div class="ant-col ant-form-item-label"><label class="ant-form-item-required" title="上级菜单目录">上级菜单目录</label></div>
              <TreeSelect
                placeholder="请选择菜单目录"
                showSearch={true}
                treeDefaultExpandedKeys={['1']}
                treeDataSimpleMode
                style={{ width: '100%' }}
                value={menuId}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                onChange={selectMenuChange}
                // loadData={onLoadData}
                treeData={treeData}
              />
            </Col>
          </Row>
          <Row gutter={[16, 16]}>
            <Col span={12} order={1}>
              <ProFormSelect
                width="xl"
                options={[
                  {
                    value: "0",
                    label: "zip包下载",
                  },
                  {
                    value: "1",
                    label: "生成到指定路径",
                  }
                ]}
                placeholder="请选择生成方式"
                name="gen_type"
                label="生成方式"
                fieldProps={{
                  onChange: (val) => {
                    if (val == 1) {
                      setShowGenPath(true);
                    } else {
                      setShowGenPath(false);
                    }
                  }
                }}
              />
            </Col>
            <Col span={12} order={2}>
              <ProFormText
                hidden={!showGenPath}
                label='生成路径'
                rules={[
                  {
                    required: true,
                    message: "生成路径不可为空。",
                  },
                ]}
                width="xl"
                name="gen_path"
                placeholder="请输入生成路径"
              />
            </Col>
          </Row>
        </Card>
        <Card title="字段信息设置" style={{ width: '100%' }}>
          {/* <Table pagination={false} columns={columns} dataSource={data} /> */}
          <Form.List name="fieldList">
            {(fields, { add, remove }) => (
              <>
                {fields.map((field, index) => {
                  return (
                    <Space key={field.key} align="baseline">
                      <Form.Item
                        {...field}
                        label="字段名称"
                        name={[field.name, 'field_name']}
                        fieldKey={[field.fieldKey, 'field_name']}
                      >
                        <Input disabled />
                        {/* {data[index].field_comment} */}
                      </Form.Item>
                      <Form.Item
                        {...field}
                        label="字段描述"
                        name={[field.name, 'field_comment']}
                        fieldKey={[field.fieldKey, 'field_comment']}
                      >
                        <Input disabled />
                      </Form.Item>
                      <Form.Item
                        {...field}
                        label="编辑"
                        style={{ width: '40px' }}
                        name={[field.name, 'f_operat']}
                        fieldKey={[field.fieldKey, 'f_operat']}
                        // rules={[{ required: true, message: 'Missing price' }]}
                        valuePropName={data[index].f_operat ? 'checked' : ''}
                      >
                        <Switch />
                      </Form.Item>
                      <Form.Item
                        {...field}
                        label="列表"
                        style={{ width: '40px' }}
                        name={[field.name, 'f_list']}
                        fieldKey={[field.fieldKey, 'f_list']}
                        valuePropName={data[index].f_list ? 'checked' : ''}
                      >
                        <Switch />
                      </Form.Item>
                      <Form.Item
                        {...field}
                        label="查询"
                        style={{ width: '40px' }}
                        name={[field.name, 'f_query']}
                        fieldKey={[field.fieldKey, 'f_query']}
                        valuePropName={data[index].f_query ? 'checked' : ''}
                      >
                        <Switch />
                      </Form.Item>
                      <Form.Item
                        {...field}
                        label="查询方式"
                        name={[field.name, 'query_type']}
                        fieldKey={[field.fieldKey, 'query_type']}
                      >
                        <Select style={{ width: 130 }}>
                          <Option value="="> 等于 </Option>
                          <Option value="!="> 不等于 </Option>
                          <Option value=">"> 大于 </Option>
                          <Option value=">="> 大于等于 </Option>
                          <Option value="<"> 小于 </Option>
                          <Option value="<="> 小于等于 </Option>
                          <Option value="like"> like </Option>
                          <Option value="is null"> is null </Option>
                          <Option value="is not null">
                            is not null
                          </Option>
                        </Select>
                      </Form.Item>
                      <Form.Item
                        {...field}
                        label="校验规则"
                        name={[field.name, 'verify_rule']}
                        fieldKey={[field.fieldKey, 'verify_rule']}
                      >
                        <Select style={{ width: 130 }}>
                          <Option value="required"> required </Option>
                        </Select>
                      </Form.Item>
                      <Form.Item
                        {...field}
                        label="显示类型"
                        name={[field.name, 'show_type']}
                        fieldKey={[field.fieldKey, 'show_type']}
                      >
                        <Select style={{ width: 130 }}>
                          <Option value="1"> 文本框 </Option>
                          <Option value="2"> 文本域 </Option>
                          <Option value="3"> 下拉框 </Option>
                          <Option value="4"> 单选框 </Option>
                          <Option value="5"> 复选框 </Option>
                          <Option value="6"> 富文本 </Option>
                          <Option value="7"> 日期控件 </Option>
                          <Option value="8"> 上传控件 </Option>
                        </Select>
                      </Form.Item>
                      <Form.Item
                        {...field}
                        label="选项内容"
                        name={[field.name, 'option_content']}
                        fieldKey={[field.fieldKey, 'option_content']}
                      >
                        <Input />
                      </Form.Item>
                      <Form.Item
                        {...field}
                        label="默认值"
                        name={[field.name, 'default_value']}
                        fieldKey={[field.fieldKey, 'default_value']}
                      >
                        <Input />
                      </Form.Item>
                      <Form.Item
                        {...field}
                        label="排序"
                        name={[field.name, 'order_by']}
                        fieldKey={[field.fieldKey, 'order_by']}
                      >
                        <Input />
                      </Form.Item>
                      {/* <Button type="dashed" onClick={() => remove(field.name)} block>
                      删除 {field.name}
                    </Button> */}
                    </Space>
                  )
                })}

                {/* <Form.Item>
                  <Button type="dashed" onClick={() => {
                    add();
                  }} block>
                    新增
                  </Button>
                </Form.Item> */}
              </>
            )}
          </Form.List>
        </Card>
        <Card title="树结构信息设置" style={{ width: '100%',display:tempType=='1'?'block':'none' }}>
          <Row gutter={[16, 16]}>
            <Col span={12} order={1}>
              <ProFormSelect width="xl"
                options={fieldData}
                name="tree_pid"
                label='父节点字段'
                placeholder="请选择父节点字段" />
            </Col>
            <Col span={12} order={1}>
              <ProFormSelect width="xl"
                options={fieldData}
                name="tree_name"
                label='节点名称字段'
                placeholder="请选择节点名称字段" />
            </Col>
          </Row>
        </Card>
        <Card title="其他信息设置" style={{ width: '100%' }}>
          <Row gutter={[16, 16]}>
            <Col span={24} order={1}>
              <ProFormText
                name="order_by"
                label={intl.formatMessage({
                  id: '排序',
                  defaultMessage: '排序',
                })}
                width="xl"
                placeholder="请输入排序"
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="请输入排序！"
                        defaultMessage="请输入排序！"
                      />
                    ),
                  },
                ]}
              />
            </Col>
          </Row>
          <Row gutter={[16, 16]}>
            <Col span={24} order={1}>
              <ProFormTextArea width="xl" name="remark" label={intl.formatMessage({
                id: '备注',
                defaultMessage: '备注',
              })}
                placeholder="请输入备注"
              />
            </Col>
          </Row>
        </Card>
      </Form>
    </Modal >
  );
};

export default UpdateForm;
